﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample96
{
    public class LightSystem : ComponentSystem
    {
        private PointLight _PointLight = new PointLight(new Vector3(200, 200, 0), new LightStrength(0.7f, 0.7f, 0.7f, 1.0f));

        private double lightFWJ;
        private Ambient Ambient = new Ambient(0.15f, 0.15f, 0.15f, 1.0f);

        public LightSystem()
        {
        }

        public override void Initialization()
        {
            ContextManager.Foreach<LightGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                var obj = context.GetContextRenderObject();
                var render = context.GetContextRenderGroup();
                var camera = render.Camera;
                Span<Vector4> data = stackalloc Vector4[]
                {
                    new Vector4(camera.EyePosition, 1),
                    _PointLight.Position,
                    Ambient,
                    _PointLight.Strength,
                    _PointLight.Strength
                };
                Span<byte> p = MemoryMarshal.AsBytes(data);
                render.PushDataToTexture(p, 0, 0);
            });
        }

        public override void Update(TimeSpan lastStamp)
        {
            lightFWJ += 0.2f;
            float tempLx = (float)(Math.Sin(lightFWJ / 180 * Math.PI) * 150);
            float tempLz = (float)(Math.Cos(lightFWJ / 180 * Math.PI) * 150);
            _PointLight.ChangePosition(new Vector3(tempLx, 200, tempLz));
            if (lightFWJ >= 360) lightFWJ = 0;
            ContextManager.Foreach<LightGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                var obj = context.GetContextRenderObject();
                var render = context.GetContextRenderGroup();
                var camera = render.Camera;
                Span<Vector4> data = stackalloc Vector4[]
                {
                    new Vector4(camera.EyePosition, 1),
                    _PointLight.Position,
                    Ambient,
                    _PointLight.Strength,
                    _PointLight.Strength
                };
                Span<byte> p = MemoryMarshal.AsBytes(data);
                render.PushDataToTexture(p, 0, 0);
            });
        }
    }

    public struct LightGroup
    {
        public Entity Entity;
        public LightComponent Light;
    }
}
